package com.spdzen.support;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * Response工具类
 * 提供返回JSON、JSONP格式数据和文件下载方法。
 * @author accountwcx@qq.com
 *
 */
public class ResponseUtils {
	private static String encoding = "utf-8";
	private static SerializerFeature[] features =  new SerializerFeature[] {
		SerializerFeature.WriteMapNullValue,
		SerializerFeature.WriteNullBooleanAsFalse,
		SerializerFeature.WriteNullListAsEmpty,
		SerializerFeature.WriteNullNumberAsZero,
		SerializerFeature.WriteNullStringAsEmpty,
		SerializerFeature.WriteDateUseDateFormat
	};
	
	public static String getEncoding() {
		return encoding;
	}

	public static void setEncoding(String encoding) {
		ResponseUtils.encoding = encoding;
	}
	
	private static String toJSONString(Object obj) {
		return JSON.toJSONString(obj, features);
	}
	
	public static void responseText(HttpServletResponse response, String text) throws IOException {
		responseText(response, text, encoding);
	}

	/**
	 * 返回文本
	 * @param response
	 * @param text 文本内容
	 * @param encoding 文本的编码格式
	 * @throws IOException 
	 */
	public static void responseText(HttpServletResponse response, String text, String encoding) throws IOException {
		response.setContentType("text/plain;charset=" + encoding);
		response.setCharacterEncoding(encoding);
		
		PrintWriter out = response.getWriter();
		out.write(text);
		out.flush();
	}
	
	/**
	 * 返回JSON格式数据，使用默认编码
	 * @param response
	 * @param data JSON数据对象
	 * @throws IOException 
	 */
	public static void responseJson(HttpServletResponse response, Object data) throws IOException{
		responseText(response, toJSONString(data), encoding);
	}
	
	public static void responseJsonp(HttpServletResponse response, Object data) throws IOException{
		String callback = "callback";
		responseJsonp(response, callback, data, encoding);
	}
	
	/**
	 * 返回JSONP数据，使用默认编码
	 * @param callback JSONP回调函数名称
	 * @param data JSONP数据对象
	 * @throws IOException 
	 */
	public static void responseJsonp(HttpServletResponse response, String callback, Object data) throws IOException{
		responseJsonp(response, callback, data, encoding);
	}
	
	/**
	 * 返回JSONP数据
	 * @param callback JSONP回调函数名称
	 * @param data JSONP数据
	 * @param encoding JSONP数据编码
	 * @throws IOException 
	 */
	public static void responseJsonp(HttpServletResponse response, String callback, Object data, String encoding) throws IOException{
		StringBuilder sb = new StringBuilder(callback);
		sb.append("(");
		sb.append(toJSONString(data));
		sb.append(");");
		responseText(response, sb.toString(), encoding);
	}
	
	/**
	 * 文件下载
	 * @param response
	 * @param file 文件
	 * @throws IOException 
	 */
	public static void download(HttpServletResponse response, File file) throws IOException{
		String fileName = file.getName();
		InputStream is = new FileInputStream(file);
		download(response, is, fileName, encoding);
	}
	
	/**
	 * 文件下载
	 * @param response
	 * @param file 文件
	 * @param fileName 客户端下载显示的文件名，如果为空则使用file.getName()获取文件名
	 * @throws IOException 
	 */
	public static void download(HttpServletResponse response, File file, String fileName) throws IOException {
		if(fileName == null || fileName.trim().isEmpty()) {
			fileName = file.getName();
		}
		InputStream is = new FileInputStream(file);
		download(response, is, fileName, encoding);
	}
	
	/**
	 * 文件下载
	 * @param response
	 * @param file 文件
	 * @param fileName 客户端下载显示的文件名，如果为空则使用file.getName()获取文件名
	 * @param encoding 文件名编码
	 * @throws IOException 
	 */
	public static void download(HttpServletResponse response, File file, String fileName, String encoding) throws IOException {
		if(fileName == null || fileName.trim().isEmpty()) {
			fileName = file.getName();
		}
		InputStream is = new FileInputStream(file);
		download(response, is, fileName, encoding);
	}
	
	/**
	 * 文件下载
	 * @param response
	 * @param filePath 文件在服务端的磁盘路径
	 * @throws IOException 
	 */
	public static void download(HttpServletResponse response, String filePath) throws IOException {
		File file = new File(filePath);
		String fileName = file.getName();
		InputStream is = new FileInputStream(file);
		download(response, is, fileName, encoding);
	}
	
	/**
	 * 文件下载
	 * @param response
	 * @param filePath 文件在服务端的磁盘路径
	 * @param fileName 客户端下载显示的文件名，如果为空则使用file.getName()获取文件名
	 * @throws IOException 
	 */
	public static void download(HttpServletResponse response, String filePath, String fileName) throws IOException {
		File file = new File(filePath);
		
		if(fileName == null || fileName.trim().isEmpty()){
			fileName = file.getName();
		}
		
		InputStream is = new FileInputStream(file);
		download(response, is, fileName, encoding);		
	}
	
	/**
	 * 文件下载
	 * @param response
	 * @param filePath 文件在服务端的磁盘路径
	 * @param fileName 客户端下载显示的文件名，如果为空则使用file.getName()获取文件名
	 * @param encoding 编码
	 * @throws IOException 
	 */
	public static void download(HttpServletResponse response, String filePath, String fileName, String encoding) throws IOException {
		File file = new File(filePath);
		
		if(fileName == null || fileName.trim().isEmpty()){
			fileName = file.getName();
		}
		
		InputStream is = new FileInputStream(file);
		download(response, is, fileName, encoding);
	}
	
	/**
	 * 文件下载
	 * @param response
	 * @param is 文件输入流
	 * @param fileName 客户端下载显示的文件名，不能为空
	 * @throws IOException
	 */
	public static void download(HttpServletResponse response, InputStream is, String fileName) throws IOException{
		download(response, is, fileName, encoding);
	}
	
	/**
	 * 文件下载
	 * @param response
	 * @param is 文件输入流
	 * @param fileName 客户端下载显示的文件名，不能为空
	 * @param encoding 编码格式
	 * @throws IOException 
	 */
	public static void download(HttpServletResponse response, InputStream is, String fileName, String encoding) throws IOException{
		if(is == null || fileName == null || fileName.trim().isEmpty()) {
			throw new IllegalArgumentException("参数不符合要求！");
		}
		
		//BufferedInputStream bis = null;
		OutputStream os = null;
		BufferedOutputStream bos = null;
		
		try{
			//bis = new BufferedInputStream(is);
			os = response.getOutputStream();
			bos = new BufferedOutputStream(os);
			response.setContentType("application/octet-stream;charset=" + encoding);
			response.setCharacterEncoding(encoding);
	        response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName, encoding));
	        byte[] buffer = new byte[1024];
	        int len = is.read(buffer);
	        while(len != -1){
	        	bos.write(buffer, 0, len);
	        	len = is.read(buffer);
	        }
	        
	        bos.flush();
		} finally {			
			if(is != null){
				is.close();
			}
		}
	}
}
